<template>
  <div class="editable-rate">
    <el-rate
      :model-value="currentValue"
      :disabled="!editable"
      :show-score="showScore"
      :text-color="textColor"
      :max="max"
      class="rate-component"
      @change="handleRateChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { reportApi } from "@/api/report-api";

interface Props {
  modelValue: number;
  editable?: boolean;
  showScore?: boolean;
  textColor?: string;
  max?: number;
  confirmTitle?: string;
  confirmMessage?: string;
  dataType: number; // 数据类型：改为 number 类型
  dataId: string | number; // 数据ID
}

const props = withDefaults(defineProps<Props>(), {
  editable: true,
  showScore: true,
  textColor: "#ff9900",
  max: 5,
  confirmTitle: "确认修改",
  confirmMessage: "确定要修改关注星级吗？"
});

const emit = defineEmits<{
  "update:modelValue": [value: number];
  change: [value: number];
}>();

const { t } = useI18n();
const currentValue = computed(() => props.modelValue);
const loading = ref(false);

const handleRateChange = async (newValue: number) => {
  if (!props.editable || newValue === props.modelValue) {
    return;
  }

  try {
    // 显示二次确认对话框
    await ElMessageBox.confirm(props.confirmMessage, props.confirmTitle, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    loading.value = true;

    // 调用统一的更新关注度接口
    await reportApi.updateAttention({
      value: newValue,
      dataType: props.dataType,
      dataId: props.dataId
    });

    ElMessage.success("关注星级修改成功");

    // 更新值
    emit("update:modelValue", newValue);
    emit("change", newValue);
  } catch (error) {
    if (error !== "cancel") {
      console.error("更新关注星级失败:", error);
      ElMessage.error("关注星级修改失败");
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.editable-rate {
  .rate-component {
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }

  :deep(.el-rate__item) {
    transition: all 0.2s ease;

    &:hover {
      transform: scale(1.1);
    }
  }
}
</style>
